package com.ah.suams.controller;

import com.ah.suams.bean.Admin;
import com.ah.suams.util.VCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class UtilController {

    @RequestMapping("/")
    public String index(@SessionAttribute Admin admin, Model model) {
        model.addAttribute("admin",admin);
        return "index";
    }

    //生成验证码图片
    @RequestMapping("/vcode")
    public void vcode(HttpServletRequest request, HttpServletResponse response) {
        //设置宽高
        int height = 38;
        int width = 78;

        //创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //图片绘画，添加文本
        String vcode = VCodeUtil.drawImage(image, width, height);
        request.getSession().setAttribute("vcode", vcode);

        //必须设置响应内容类型为图片，否则不识别
        response.setContentType("image/png");

        OutputStream os = null; //获取文件输出流
        try {
            os = response.getOutputStream();

            //输出图片流
            ImageIO.write(image, "png", os);

            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
